package org.jeecg.modules.system.service.impl;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CacheConstant;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.constant.DataBaseConstant;
import org.jeecg.common.constant.MaterialConstant;
import org.jeecg.common.constant.WebsocketConst;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.vo.ComboModel;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.common.system.vo.DynamicDataSourceModel;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.system.vo.SysCategoryModel;
import org.jeecg.common.system.vo.SysDepartModel;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.IPUtils;
import org.jeecg.common.util.MinioUtil;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.common.util.SysAnnmentTypeEnum;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.common.util.dingtalk.DingMessageUtils;
import org.jeecg.common.util.oss.OssBootUtil;
import org.jeecg.modules.message.entity.SysMessageTemplate;
import org.jeecg.modules.message.service.ISysMessageTemplateService;
import org.jeecg.modules.message.websocket.WebSocket;
import org.jeecg.modules.quartz.entity.SysJobQueue;
import org.jeecg.modules.quartz.service.ISysJobQueueService;
import org.jeecg.modules.system.entity.SysAnnouncement;
import org.jeecg.modules.system.entity.SysAnnouncementSend;
import org.jeecg.modules.system.entity.SysCategory;
import org.jeecg.modules.system.entity.SysDataSource;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.entity.SysDict;
import org.jeecg.modules.system.entity.SysFillRule;
import org.jeecg.modules.system.entity.SysLog;
import org.jeecg.modules.system.entity.SysRole;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.mapper.SysAnnouncementMapper;
import org.jeecg.modules.system.mapper.SysAnnouncementSendMapper;
import org.jeecg.modules.system.mapper.SysCategoryMapper;
import org.jeecg.modules.system.mapper.SysDepartMapper;
import org.jeecg.modules.system.mapper.SysLogMapper;
import org.jeecg.modules.system.mapper.SysRoleMapper;
import org.jeecg.modules.system.mapper.SysUserMapper;
import org.jeecg.modules.system.mapper.SysUserRoleMapper;
import org.jeecg.modules.system.service.ISysDataSourceService;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysDictService;
import org.jeecg.modules.system.service.ISysFillRuleService;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import io.finer.erp.jeecg.bas.entity.BasCustomer;
import io.finer.erp.jeecg.bas.entity.BasMaterial;
import io.finer.erp.jeecg.bas.entity.BasMaterialCategory;
import io.finer.erp.jeecg.bas.entity.BasSequence;
import io.finer.erp.jeecg.bas.entity.ZrkOrderProduct;
import io.finer.erp.jeecg.bas.entity.ZrkPushSet;
import io.finer.erp.jeecg.bas.entity.ZrkQzOrder;
import io.finer.erp.jeecg.bas.entity.ZrkShoporder;
import io.finer.erp.jeecg.bas.entity.ZzDevice;
import io.finer.erp.jeecg.bas.entity.ZzShoporder;
import io.finer.erp.jeecg.bas.service.IBasCustomerService;
import io.finer.erp.jeecg.bas.service.IBasMaterialCategoryService;
import io.finer.erp.jeecg.bas.service.IBasMaterialService;
import io.finer.erp.jeecg.bas.service.IBasSequenceService;
import io.finer.erp.jeecg.bas.service.IZrkMesFqParamService;
import io.finer.erp.jeecg.bas.service.IZrkOrderProductService;
import io.finer.erp.jeecg.bas.service.IZrkProductCustomerService;
import io.finer.erp.jeecg.bas.service.IZrkPushSetService;
import io.finer.erp.jeecg.bas.service.IZrkQzOrderService;
import io.finer.erp.jeecg.bas.service.IZrkShoporderService;
import io.finer.erp.jeecg.bas.service.IZzDeviceService;
import io.finer.erp.jeecg.bas.service.IZzShoporderService;
import io.finer.erp.jeecg.bas.vo.ZrkMesFqParamVO;
import io.finer.erp.jeecg.bas.vo.ZrkProductCustomerVO;
import io.finer.erp.jeecg.stock.entity.StkIoBill;
import io.finer.erp.jeecg.stock.entity.StkIoBillEntry;
import io.finer.erp.jeecg.stock.entity.StkPickUpBill;
import io.finer.erp.jeecg.stock.entity.StkPickUpEntry;
import io.finer.erp.jeecg.stock.service.IStkIoBillEntryService;
import io.finer.erp.jeecg.stock.service.IStkIoBillService;
import io.finer.erp.jeecg.stock.service.IStkPickUpBillService;
import io.finer.erp.jeecg.stock.service.IStkPickUpEntryService;
import lombok.extern.slf4j.Slf4j;

/**
 * @Description: 底层共通业务API，提供其他独立模块调用
 * @Author: scott
 * @Date:2019-4-20 
 * @Version:V1.0
 */
@Slf4j
@Service
public class SysBaseApiImpl implements ISysBaseAPI {
	/** 当前系统数据库类型 */
	private static String DB_TYPE = "";
	@Autowired
	private ISysMessageTemplateService sysMessageTemplateService;
	@Resource
	private SysLogMapper sysLogMapper;
	@Autowired
	private SysUserMapper userMapper;
	@Autowired
	private SysUserRoleMapper sysUserRoleMapper;
	@Autowired
	private ISysDepartService sysDepartService;
	@Autowired
	private ISysDictService sysDictService;
	@Resource
	private SysAnnouncementMapper sysAnnouncementMapper;
	@Resource
	private SysAnnouncementSendMapper sysAnnouncementSendMapper;
	@Resource
    private WebSocket webSocket;
	@Resource
	private SysRoleMapper roleMapper;
	@Resource
	private SysDepartMapper departMapper;
	@Resource
	private SysCategoryMapper categoryMapper;
	@Autowired
	private ISysJobQueueService jobQueueService;

	@Autowired
	private ISysDataSourceService dataSourceService;
	@Autowired
	private IStkPickUpBillService stkPickUpBillService;
	@Autowired
	private ISysMessageTemplateService msgTemService;
	@Autowired
	private IZrkPushSetService pushSetService;
	@Autowired
	private ISysUserService sysUserService;
	@Autowired
	private ISysBaseAPI sysBaseApi;
	@Autowired
	private IStkPickUpEntryService pickUpEntryService;
	@Autowired
	private IBasMaterialCategoryService categoryService;
	@Autowired
	private IZrkQzOrderService zrkQzOrderService;
	@Autowired
	private IZrkShoporderService zrkShoporderService;
	@Autowired
	private IZrkOrderProductService zrkOrderProductService;
	@Autowired
	private IZzShoporderService zzShoporderService;
	@Autowired
	private IZzDeviceService zzDeviceService;
	@Autowired
	private IStkIoBillService stkIoBillService;
	@Autowired
	private IStkIoBillEntryService stkIoBillEntryService;
	@Autowired
	private IBasCustomerService basCustomerService;
	@Autowired
	private IBasMaterialService materialService;
	@Autowired
	private ISysFillRuleService fillRuleService;
	@Autowired
	private IBasSequenceService sequenceService;
	@Autowired
	private IZrkMesFqParamService zrkMesFqParamService;
	@Autowired
	private IZrkProductCustomerService productCustomerService;
	@Autowired
	private RedisUtil redisUtil;
	
	@Override
	public void addLog(String LogContent, Integer logType, Integer operatetype) {
		SysLog sysLog = new SysLog();
		//注解上的描述,操作日志内容
		sysLog.setLogContent(LogContent);
		sysLog.setLogType(logType);
		sysLog.setOperateType(operatetype);

		//请求的方法名
		//请求的参数

		try {
			//获取request
			HttpServletRequest request = SpringContextUtils.getHttpServletRequest();
			//设置IP地址
			sysLog.setIp(IPUtils.getIpAddr(request));
		} catch (Exception e) {
			sysLog.setIp("127.0.0.1");
		}

		//获取登录用户信息
		LoginUser sysUser = (LoginUser)SecurityUtils.getSubject().getPrincipal();
		if(sysUser!=null){
			sysLog.setUserid(sysUser.getUsername());
			sysLog.setUsername(sysUser.getRealname());

		}
		sysLog.setCreateTime(new Date());
		//保存系统日志
		sysLogMapper.insert(sysLog);
	}

	@Override
	@Cacheable(cacheNames=CacheConstant.SYS_USERS_CACHE, key="#username")
	public LoginUser getUserByName(String username) {
		if(oConvertUtils.isEmpty(username)) {
			return null;
		}
		LoginUser loginUser = new LoginUser();
		SysUser sysUser = userMapper.getUserByName(username);
		if(sysUser==null) {
			return null;
		}
		BeanUtils.copyProperties(sysUser, loginUser);
		return loginUser;
	}
	
	@Override
	public LoginUser getUserById(String id) {
		if(oConvertUtils.isEmpty(id)) {
			return null;
		}
		LoginUser loginUser = new LoginUser();
		SysUser sysUser = userMapper.selectById(id);
		if(sysUser==null) {
			return null;
		}
		BeanUtils.copyProperties(sysUser, loginUser);
		return loginUser;
	}

	@Override
	public List<String> getRolesByUsername(String username) {
		return sysUserRoleMapper.getRoleByUserName(username);
	}

	@Override
	public List<String> getDepartIdsByUsername(String username) {
		List<SysDepart> list = sysDepartService.queryDepartsByUsername(username);
		List<String> result = new ArrayList<>(list.size());
		for (SysDepart depart : list) {
			result.add(depart.getId());
		}
		return result;
	}

	@Override
	public List<String> getDepartNamesByUsername(String username) {
		List<SysDepart> list = sysDepartService.queryDepartsByUsername(username);
		List<String> result = new ArrayList<>(list.size());
		for (SysDepart depart : list) {
			result.add(depart.getDepartName());
		}
		return result;
	}

	@Override
	public String getDatabaseType() throws SQLException {
		if(oConvertUtils.isNotEmpty(DB_TYPE)){
			return DB_TYPE;
		}
		DataSource dataSource = SpringContextUtils.getApplicationContext().getBean(DataSource.class);
		return getDatabaseTypeByDataSource(dataSource);
	}

	@Override
	@Cacheable(value = CacheConstant.SYS_DICT_CACHE,key = "#code")
	public List<DictModel> queryDictItemsByCode(String code) {
		return sysDictService.queryDictItemsByCode(code);
	}

	@Override
	public List<DictModel> queryTableDictItemsByCode(String table, String text, String code) {
		return sysDictService.queryTableDictItemsByCode(table, text, code);
	}

	@Override
	public List<DictModel> queryAllDepartBackDictModel() {
		return sysDictService.queryAllDepartBackDictModel();
	}

    @Override
    public List<JSONObject> queryAllDepart(Wrapper wrapper) {
        //noinspection unchecked
        return JSON.parseArray(JSON.toJSONString(sysDepartService.list(wrapper))).toJavaList(JSONObject.class);
    }

    @Override
	public void sendSysAnnouncement(String fromUser, String toUser, String title, String msgContent) {
		this.sendSysAnnouncement(fromUser, toUser, title, msgContent, CommonConstant.MSG_CATEGORY_2);
	}

	@Override
	public void sendSysAnnouncement(String fromUser, String toUser, String title, String msgContent, String setMsgCategory) {
		SysAnnouncement announcement = new SysAnnouncement();
		announcement.setTitile(title);
		announcement.setMsgContent(msgContent);
		announcement.setSender(fromUser);
		announcement.setPriority(CommonConstant.PRIORITY_M);
		announcement.setMsgType(CommonConstant.MSG_TYPE_UESR);
		announcement.setSendStatus(CommonConstant.HAS_SEND);
		announcement.setSendTime(new Date());
		announcement.setMsgCategory(setMsgCategory);
		announcement.setDelFlag(String.valueOf(CommonConstant.DEL_FLAG_0));
		sysAnnouncementMapper.insert(announcement);
		// 2.插入用户通告阅读标记表记录
		String userId = toUser;
		String[] userIds = userId.split(",");
		String anntId = announcement.getId();
		for(int i=0;i<userIds.length;i++) {
			if(oConvertUtils.isNotEmpty(userIds[i])) {
				SysUser sysUser = userMapper.getUserByName(userIds[i]);
				if(sysUser==null) {
					continue;
				}
				SysAnnouncementSend announcementSend = new SysAnnouncementSend();
				announcementSend.setAnntId(anntId);
				announcementSend.setUserId(sysUser.getId());
				announcementSend.setReadFlag(CommonConstant.NO_READ_FLAG);
				sysAnnouncementSendMapper.insert(announcementSend);
				JSONObject obj = new JSONObject();
		    	obj.put(WebsocketConst.MSG_CMD, WebsocketConst.CMD_USER);
		    	obj.put(WebsocketConst.MSG_USER_ID, sysUser.getId());
				obj.put(WebsocketConst.MSG_ID, announcement.getId());
				obj.put(WebsocketConst.MSG_TXT, announcement.getTitile());
		    	webSocket.sendOneMessage(sysUser.getId(), obj.toJSONString());
			}
		}

	}

	@Override
	public void sendSysAnnouncement(String fromUser, String toUser, String title, String msgContent, String setMsgCategory, String busType, String busId) {
		SysAnnouncement announcement = new SysAnnouncement();
		announcement.setTitile(title);
		announcement.setMsgContent(msgContent);
		announcement.setSender(fromUser);
		announcement.setPriority(CommonConstant.PRIORITY_M);
		announcement.setMsgType(CommonConstant.MSG_TYPE_UESR);
		announcement.setSendStatus(CommonConstant.HAS_SEND);
		announcement.setSendTime(new Date());
		announcement.setMsgCategory(setMsgCategory);
		announcement.setDelFlag(String.valueOf(CommonConstant.DEL_FLAG_0));
		announcement.setBusId(busId);
		announcement.setBusType(busType);
		announcement.setOpenType(SysAnnmentTypeEnum.getByType(busType).getOpenType());
		announcement.setOpenPage(SysAnnmentTypeEnum.getByType(busType).getOpenPage());
		sysAnnouncementMapper.insert(announcement);
		// 2.插入用户通告阅读标记表记录
		String userId = toUser;
		String[] userIds = userId.split(",");
		String anntId = announcement.getId();
		for(int i=0;i<userIds.length;i++) {
			if(oConvertUtils.isNotEmpty(userIds[i])) {
				SysUser sysUser = userMapper.getUserByName(userIds[i]);
				if(sysUser==null) {
					continue;
				}
				SysAnnouncementSend announcementSend = new SysAnnouncementSend();
				announcementSend.setAnntId(anntId);
				announcementSend.setUserId(sysUser.getId());
				announcementSend.setReadFlag(CommonConstant.NO_READ_FLAG);
				sysAnnouncementSendMapper.insert(announcementSend);
				JSONObject obj = new JSONObject();
				obj.put(WebsocketConst.MSG_CMD, WebsocketConst.CMD_USER);
				obj.put(WebsocketConst.MSG_USER_ID, sysUser.getId());
				obj.put(WebsocketConst.MSG_ID, announcement.getId());
				obj.put(WebsocketConst.MSG_TXT, announcement.getTitile());
				webSocket.sendOneMessage(sysUser.getId(), obj.toJSONString());
			}
		}
	}

	@Override
	public void updateSysAnnounReadFlag(String busType, String busId) {
		SysAnnouncement announcement = sysAnnouncementMapper.selectOne(new QueryWrapper<SysAnnouncement>().eq("bus_type",busType).eq("bus_id",busId));
		if(announcement != null){
			LoginUser sysUser = (LoginUser)SecurityUtils.getSubject().getPrincipal();
			String userId = sysUser.getId();
			LambdaUpdateWrapper<SysAnnouncementSend> updateWrapper = new UpdateWrapper().lambda();
			updateWrapper.set(SysAnnouncementSend::getReadFlag, CommonConstant.HAS_READ_FLAG);
			updateWrapper.set(SysAnnouncementSend::getReadTime, new Date());
			updateWrapper.last("where annt_id ='"+announcement.getId()+"' and user_id ='"+userId+"'");
			SysAnnouncementSend announcementSend = new SysAnnouncementSend();
			sysAnnouncementSendMapper.update(announcementSend, updateWrapper);
		}
	}

	@Override
    public String parseTemplateByCode(String templateCode,Map<String, String> map) {
        List<SysMessageTemplate> sysSmsTemplates = sysMessageTemplateService.selectByCode(templateCode);
        if(sysSmsTemplates==null||sysSmsTemplates.size()==0){
            throw new JeecgBootException("消息模板不存在，模板编码："+templateCode);
        }
        SysMessageTemplate sysSmsTemplate = sysSmsTemplates.get(0);
        //模板内容
        String content = sysSmsTemplate.getTemplateContent();
        if(map!=null) {
            for (Map.Entry<String, String> entry : map.entrySet()) {
                String str = "${" + entry.getKey() + "}";
                content = content.replace(str, entry.getValue());
            }
        }
        return content;
    }

	@Override
	public void sendSysAnnouncement(String fromUser, String toUser,String title,Map<String, String> map, String templateCode) {
		List<SysMessageTemplate> sysSmsTemplates = sysMessageTemplateService.selectByCode(templateCode);
        if(sysSmsTemplates==null||sysSmsTemplates.size()==0){
            throw new JeecgBootException("消息模板不存在，模板编码："+templateCode);
        }
		SysMessageTemplate sysSmsTemplate = sysSmsTemplates.get(0);
		//模板标题
		title = title==null?sysSmsTemplate.getTemplateName():title;
		//模板内容
		String content = sysSmsTemplate.getTemplateContent();
		if(map!=null) {
			for (Map.Entry<String, String> entry : map.entrySet()) {
				String str = "${" + entry.getKey() + "}";
				title = title.replace(str, entry.getValue());
				content = content.replace(str, entry.getValue());
			}
		}

		SysAnnouncement announcement = new SysAnnouncement();
		announcement.setTitile(title);
		announcement.setMsgContent(content);
		announcement.setSender(fromUser);
		announcement.setPriority(CommonConstant.PRIORITY_M);
		announcement.setMsgType(CommonConstant.MSG_TYPE_UESR);
		announcement.setSendStatus(CommonConstant.HAS_SEND);
		announcement.setSendTime(new Date());
		announcement.setMsgCategory(CommonConstant.MSG_CATEGORY_2);
		announcement.setDelFlag(String.valueOf(CommonConstant.DEL_FLAG_0));
		sysAnnouncementMapper.insert(announcement);
		// 2.插入用户通告阅读标记表记录
		String userId = toUser;
		String[] userIds = userId.split(",");
		String anntId = announcement.getId();
		for(int i=0;i<userIds.length;i++) {
			if(oConvertUtils.isNotEmpty(userIds[i])) {
				SysUser sysUser = userMapper.getUserByName(userIds[i]);
				if(sysUser==null) {
					continue;
				}
				SysAnnouncementSend announcementSend = new SysAnnouncementSend();
				announcementSend.setAnntId(anntId);
				announcementSend.setUserId(sysUser.getId());
				announcementSend.setReadFlag(CommonConstant.NO_READ_FLAG);
				sysAnnouncementSendMapper.insert(announcementSend);
				JSONObject obj = new JSONObject();
				obj.put(WebsocketConst.MSG_CMD, WebsocketConst.CMD_USER);
				obj.put(WebsocketConst.MSG_USER_ID, sysUser.getId());
				obj.put(WebsocketConst.MSG_ID, announcement.getId());
				obj.put(WebsocketConst.MSG_TXT, announcement.getTitile());
				webSocket.sendOneMessage(sysUser.getId(), obj.toJSONString());
			}
		}
	}

	@Override
	public void sendSysAnnouncement(String fromUser, String toUser, String title, Map<String, String> map, String templateCode, String busType, String busId) {
		List<SysMessageTemplate> sysSmsTemplates = sysMessageTemplateService.selectByCode(templateCode);
		if(sysSmsTemplates==null||sysSmsTemplates.size()==0){
			throw new JeecgBootException("消息模板不存在，模板编码："+templateCode);
		}
		SysMessageTemplate sysSmsTemplate = sysSmsTemplates.get(0);
		//模板标题
		title = title==null?sysSmsTemplate.getTemplateName():title;
		//模板内容
		String content = sysSmsTemplate.getTemplateContent();
		if(map!=null) {
			for (Map.Entry<String, String> entry : map.entrySet()) {
				String str = "${" + entry.getKey() + "}";
				title = title.replace(str, entry.getValue());
				content = content.replace(str, entry.getValue());
			}
		}
		SysAnnouncement announcement = new SysAnnouncement();
		announcement.setTitile(title);
		announcement.setMsgContent(content);
		announcement.setSender(fromUser);
		announcement.setPriority(CommonConstant.PRIORITY_M);
		announcement.setMsgType(CommonConstant.MSG_TYPE_UESR);
		announcement.setSendStatus(CommonConstant.HAS_SEND);
		announcement.setSendTime(new Date());
		announcement.setMsgCategory(CommonConstant.MSG_CATEGORY_2);
		announcement.setDelFlag(String.valueOf(CommonConstant.DEL_FLAG_0));
		announcement.setBusId(busId);
		announcement.setBusType(busType);
		announcement.setOpenType(SysAnnmentTypeEnum.getByType(busType).getOpenType());
		announcement.setOpenPage(SysAnnmentTypeEnum.getByType(busType).getOpenPage());
		sysAnnouncementMapper.insert(announcement);
		// 2.插入用户通告阅读标记表记录
		String userId = toUser;
		String[] userIds = userId.split(",");
		String anntId = announcement.getId();
		for(int i=0;i<userIds.length;i++) {
			if(oConvertUtils.isNotEmpty(userIds[i])) {
				SysUser sysUser = userMapper.getUserByName(userIds[i]);
				if(sysUser==null) {
					continue;
				}
				SysAnnouncementSend announcementSend = new SysAnnouncementSend();
				announcementSend.setAnntId(anntId);
				announcementSend.setUserId(sysUser.getId());
				announcementSend.setReadFlag(CommonConstant.NO_READ_FLAG);
				sysAnnouncementSendMapper.insert(announcementSend);
				JSONObject obj = new JSONObject();
				obj.put(WebsocketConst.MSG_CMD, WebsocketConst.CMD_USER);
				obj.put(WebsocketConst.MSG_USER_ID, sysUser.getId());
				obj.put(WebsocketConst.MSG_ID, announcement.getId());
				obj.put(WebsocketConst.MSG_TXT, announcement.getTitile());
				webSocket.sendOneMessage(sysUser.getId(), obj.toJSONString());
			}
		}
	}

	/**
	 * 获取数据库类型
	 * @param dataSource
	 * @return
	 * @throws SQLException
	 */
	private String getDatabaseTypeByDataSource(DataSource dataSource) throws SQLException{
		if("".equals(DB_TYPE)) {
			Connection connection = dataSource.getConnection();
			try {
				DatabaseMetaData md = connection.getMetaData();
				String dbType = md.getDatabaseProductName().toLowerCase();
				if(dbType.indexOf("mysql")>=0) {
					DB_TYPE = DataBaseConstant.DB_TYPE_MYSQL;
				}else if(dbType.indexOf("oracle")>=0) {
					DB_TYPE = DataBaseConstant.DB_TYPE_ORACLE;
				}else if(dbType.indexOf("sqlserver")>=0||dbType.indexOf("sql server")>=0) {
					DB_TYPE = DataBaseConstant.DB_TYPE_SQLSERVER;
				}else if(dbType.indexOf("postgresql")>=0) {
					DB_TYPE = DataBaseConstant.DB_TYPE_POSTGRESQL;
				}else {
					throw new JeecgBootException("数据库类型:["+dbType+"]不识别!");
				}
			} catch (Exception e) {
				log.error(e.getMessage(), e);
			}finally {
				connection.close();
			}
		}
		return DB_TYPE;
		
	}

	@Override
	public List<DictModel> queryAllDict() {
		// 查询并排序
		QueryWrapper<SysDict> queryWrapper = new QueryWrapper<SysDict>();
		queryWrapper.orderByAsc("create_time");
		List<SysDict> dicts = sysDictService.list(queryWrapper);
		// 封装成 model
		List<DictModel> list = new ArrayList<DictModel>();
		for (SysDict dict : dicts) {
			list.add(new DictModel(dict.getDictCode(), dict.getDictName()));
		}

		return list;
	}

	@Override
	public List<SysCategoryModel> queryAllDSysCategory() {
		List<SysCategory> ls = categoryMapper.selectList(null);
		List<SysCategoryModel> res = oConvertUtils.entityListToModelList(ls,SysCategoryModel.class);
		return res;
	}

	@Override
	public List<DictModel> queryFilterTableDictInfo(String table, String text, String code, String filterSql) {
		return sysDictService.queryTableDictItemsByCodeAndFilter(table,text,code,filterSql);
	}

	@Override
	public List<String> queryTableDictByKeys(String table, String text, String code, String[] keyArray) {
		return sysDictService.queryTableDictByKeys(table,text,code,keyArray);
	}

	@Override
	public List<ComboModel> queryAllUser() {
		List<ComboModel> list = new ArrayList<ComboModel>();
		List<SysUser> userList = userMapper.selectList(new QueryWrapper<SysUser>().eq("status",1).eq("del_flag",0));
		for(SysUser user : userList){
			ComboModel model = new ComboModel();
			model.setTitle(user.getRealname());
			model.setId(user.getId());
			model.setUsername(user.getUsername());
			list.add(model);
		}
		return list;
	}

    @Override
    public JSONObject queryAllUser(String[] userIds,int pageNo,int pageSize) {
		JSONObject json = new JSONObject();
		QueryWrapper<SysUser> queryWrapper = new QueryWrapper<SysUser>().eq("status",1).eq("del_flag",0);
        List<ComboModel> list = new ArrayList<ComboModel>();
		Page<SysUser> page = new Page<SysUser>(pageNo, pageSize);
		IPage<SysUser> pageList = userMapper.selectPage(page, queryWrapper);
        for(SysUser user : pageList.getRecords()){
            ComboModel model = new ComboModel();
            model.setUsername(user.getUsername());
            model.setTitle(user.getRealname());
            model.setId(user.getId());
            model.setEmail(user.getEmail());
            if(oConvertUtils.isNotEmpty(userIds)){
                for(int i = 0; i<userIds.length;i++){
                    if(userIds[i].equals(user.getId())){
                        model.setChecked(true);
                    }
                }
            }
            list.add(model);
        }
		json.put("list",list);
        json.put("total",pageList.getTotal());
        return json;
    }

    @Override
    public List<JSONObject> queryAllUser(Wrapper wrapper) {
        //noinspection unchecked
        return JSON.parseArray(JSON.toJSONString(userMapper.selectList(wrapper))).toJavaList(JSONObject.class);
    }

    @Override
	public List<ComboModel> queryAllRole() {
		List<ComboModel> list = new ArrayList<ComboModel>();
		List<SysRole> roleList = roleMapper.selectList(new QueryWrapper<SysRole>());
		for(SysRole role : roleList){
			ComboModel model = new ComboModel();
			model.setTitle(role.getRoleName());
			model.setId(role.getId());
			list.add(model);
		}
		return list;
	}

    @Override
    public List<ComboModel> queryAllRole(String[] roleIds) {
        List<ComboModel> list = new ArrayList<ComboModel>();
        List<SysRole> roleList = roleMapper.selectList(new QueryWrapper<SysRole>());
        for(SysRole role : roleList){
            ComboModel model = new ComboModel();
            model.setTitle(role.getRoleName());
            model.setId(role.getId());
            model.setRoleCode(role.getRoleCode());
            if(oConvertUtils.isNotEmpty(roleIds)) {
                for (int i = 0; i < roleIds.length; i++) {
                    if (roleIds[i].equals(role.getId())) {
                        model.setChecked(true);
                    }
                }
            }
            list.add(model);
        }
        return list;
    }

	@Override
	public List<String> getRoleIdsByUsername(String username) {
		return sysUserRoleMapper.getRoleIdByUserName(username);
	}

	@Override
	public String getDepartIdsByOrgCode(String orgCode) {
		return departMapper.queryDepartIdByOrgCode(orgCode);
	}

	@Override
	public DictModel getParentDepartId(String departId) {
		SysDepart depart = departMapper.getParentDepartId(departId);
		DictModel model = new DictModel(depart.getId(),depart.getParentId());
		return model;
	}

	@Override
	public List<SysDepartModel> getAllSysDepart() {
		List<SysDepartModel> departModelList = new ArrayList<SysDepartModel>();
		List<SysDepart> departList = departMapper.selectList(new QueryWrapper<SysDepart>().eq("del_flag","0"));
		for(SysDepart depart : departList){
			SysDepartModel model = new SysDepartModel();
			BeanUtils.copyProperties(depart,model);
			departModelList.add(model);
		}
		return departModelList;
	}

	@Override
	public DynamicDataSourceModel getDynamicDbSourceById(String dbSourceId) {
		SysDataSource dbSource = dataSourceService.getById(dbSourceId);
		return new DynamicDataSourceModel(dbSource);
	}

	@Override
	public DynamicDataSourceModel getDynamicDbSourceByCode(String dbSourceCode) {
		SysDataSource dbSource = dataSourceService.getOne(new LambdaQueryWrapper<SysDataSource>().eq(SysDataSource::getCode, dbSourceCode));
		return new DynamicDataSourceModel(dbSource);
	}

	@Override
	public List<String> getDeptHeadByDepId(String deptId) {
		List<SysUser> userList = userMapper.selectList(new QueryWrapper<SysUser>().like("depart_ids",deptId).eq("status",1).eq("del_flag",0));
		List<String> list = new ArrayList<>();
		for(SysUser user : userList){
			list.add(user.getUsername());
		}
		return list;
	}

	@Override
	public String upload(MultipartFile file,String bizPath,String uploadType) {
		String url = "";
		if(CommonConstant.UPLOAD_TYPE_MINIO.equals(uploadType)){
			url = MinioUtil.upload(file,bizPath);
		}else{
			url = OssBootUtil.upload(file,bizPath);
		}
		return url;
	}

	@Override
	public String upload(MultipartFile file, String bizPath, String uploadType, String customBucket) {
		String url = "";
		if(CommonConstant.UPLOAD_TYPE_MINIO.equals(uploadType)){
			url = MinioUtil.upload(file,bizPath,customBucket);
		}else{
			url = OssBootUtil.upload(file,bizPath,customBucket);
		}
		return url;
	}

	@Override
	public void viewAndDownload(String filePath, String uploadpath, String uploadType, HttpServletResponse response) {
		InputStream inputStream = null;
		OutputStream outputStream = null;
		try {
			if(filePath.startsWith("http")){
				String fileName = filePath.substring(filePath.lastIndexOf("/")+1);
				if(CommonConstant.UPLOAD_TYPE_MINIO.equals(uploadType)){
					String bucketName = filePath.replace(MinioUtil.getMinioUrl(),"").split("/")[0];
					String objectName = filePath.replace(MinioUtil.getMinioUrl()+bucketName,"");
					inputStream = MinioUtil.getMinioFile(bucketName,objectName);
					if(inputStream == null){
						bucketName = CommonConstant.UPLOAD_CUSTOM_BUCKET;
						objectName = filePath.replace(OssBootUtil.getStaticDomain()+"/","");
						inputStream = OssBootUtil.getOssFile(objectName,bucketName);
					}
				}else{
					String bucketName = CommonConstant.UPLOAD_CUSTOM_BUCKET;
					String objectName = filePath.replace(OssBootUtil.getStaticDomain()+"/","");
					inputStream = OssBootUtil.getOssFile(objectName,bucketName);
					if(inputStream == null){
						bucketName = filePath.replace(MinioUtil.getMinioUrl(),"").split("/")[0];
						objectName = filePath.replace(MinioUtil.getMinioUrl()+bucketName,"");
						inputStream = MinioUtil.getMinioFile(bucketName,objectName);
					}
				}
				response.addHeader("Content-Disposition", "attachment;fileName=" + new String(fileName.getBytes("UTF-8"),"iso-8859-1"));
			}else{
				// 本地文件处理
				filePath = filePath.replace("..", "");
				if (filePath.endsWith(",")) {
					filePath = filePath.substring(0, filePath.length() - 1);
				}
				String fullPath = uploadpath + File.separator + filePath;
				String downloadFilePath = uploadpath + File.separator + fullPath;
				File file = new File(downloadFilePath);
				inputStream = new BufferedInputStream(new FileInputStream(fullPath));
				response.addHeader("Content-Disposition", "attachment;fileName=" + new String(file.getName().getBytes("UTF-8"),"iso-8859-1"));
			}
			response.setContentType("application/force-download");// 设置强制下载不打开
			outputStream = response.getOutputStream();
			if(inputStream != null){
				byte[] buf = new byte[1024];
				int len;
				while ((len = inputStream.read(buf)) > 0) {
					outputStream.write(buf, 0, len);
				}
				response.flushBuffer();
			}
		} catch (IOException e) {
			response.setStatus(404);
			log.error("预览文件失败" + e.getMessage());
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					log.error(e.getMessage(), e);
				}
			}
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (IOException e) {
					log.error(e.getMessage(), e);
				}
			}
		}
	}

	@Override
	public void sendWebSocketMsg(String[] userIds, String cmd) {
		JSONObject obj = new JSONObject();
		obj.put(WebsocketConst.MSG_CMD, cmd);
		webSocket.sendMoreMessage(userIds, obj.toJSONString());
	}

	@Override
	public List<LoginUser> queryAllUserByIds(String[] userIds) {
		QueryWrapper<SysUser> queryWrapper = new QueryWrapper<SysUser>().eq("status",1).eq("del_flag",0);
		queryWrapper.in("id",userIds);
		List<LoginUser> loginUsers = new ArrayList<>();
		List<SysUser> sysUsers = userMapper.selectList(queryWrapper);
		for (SysUser user:sysUsers) {
			LoginUser loginUser=new LoginUser();
			BeanUtils.copyProperties(user, loginUser);
			loginUsers.add(loginUser);
		}
		return loginUsers;
	}

	/**
	 * 推送签到人员信息
	 * @param userId
	 */
	@Override
	public void meetingSignWebsocket(String userId) {
		JSONObject obj = new JSONObject();
		obj.put(WebsocketConst.MSG_CMD, WebsocketConst.CMD_SIGN);
		obj.put(WebsocketConst.MSG_USER_ID,userId);
		//TODO 目前全部推送，后面修改
		webSocket.sendAllMessage(obj.toJSONString());
	}

	@Override
	public List<LoginUser> queryUserByNames(String[] userNames) {
		QueryWrapper<SysUser> queryWrapper = new QueryWrapper<SysUser>().eq("status",1).eq("del_flag",0);
		queryWrapper.in("username",userNames);
		List<LoginUser> loginUsers = new ArrayList<>();
		List<SysUser> sysUsers = userMapper.selectList(queryWrapper);
		for (SysUser user:sysUsers) {
			LoginUser loginUser=new LoginUser();
			BeanUtils.copyProperties(user, loginUser);
			loginUsers.add(loginUser);
		}
		return loginUsers;
	}



	@Override
	public Result<?> sendDdMessage(String ids,String orderNo) {
		if(oConvertUtils.isEmpty(orderNo)) {
			return Result.error("未找到销售单");
		}
		StkPickUpBill pickUpBill = stkPickUpBillService.getById(ids);
		//如果没有推送消息，则进行推送
		if(pickUpBill != null && pickUpBill.getIsPush() != null && pickUpBill.getIsPush() == 0) {
			if(StringUtils.equals(pickUpBill.getType(), "0")) {
				return sendTHMessage(pickUpBill,orderNo);
			}else if(StringUtils.equals(pickUpBill.getType(), "1")){
				return sendCheckOutMessage(pickUpBill,orderNo);
			}
		} else {
			if(pickUpBill == null) {
				return Result.error("没找到提货单");
			} else {
				return Result.error("消息已经发送");
			}

		}
		return Result.error("未知错误");
	}
	
	private Result<?> sendTHMessage(StkPickUpBill pickUpBill,String orderId) {
		String[] orderIdArray = StringUtils.split(orderId, ",");
		List<String> orderIdList = Arrays.asList(orderIdArray);
		//查询工单信息
		List<ZzShoporder> order = zzShoporderService.listByIds(orderIdList);
		List<String> woCodeList = Lists.newArrayList();
		StringBuffer orderNo = new StringBuffer();
		if(order!=null && order.size()>0) {
			for(ZzShoporder shoporder:order) {
				orderNo.append(shoporder.getOrderNo());
				woCodeList.add(shoporder.getWoCode());
			}
		}
		//您有新的提货单等待提货，销售单号为：${processNo},Mes单号为：${id},机器号：${deviceName},客户名：${customerName},明细为：${info},消息提醒时间：${messageTime},请尽快登录后台管理系统进行提货单出库！
		//取出消息模板
		SysMessageTemplate template = msgTemService.lambdaQuery().eq(SysMessageTemplate::getTemplateCode, "zrk_new_thd").one();
		String mesId = pickUpBill.getMesId();
		ZrkQzOrder qzOrder = this.zrkQzOrderService.getById(mesId);
		if(null == qzOrder) {
			return Result.error("未找到mes单");
		}
		//mes单号
		StringBuffer mesCode = new StringBuffer();
		if(oConvertUtils.isEmpty(qzOrder.getCode())) {
			mesCode.append("无");
		}else {
			mesCode.append(qzOrder.getCode());
			mesCode.append("(");
			//判断是否是复合工序
			if(StringUtils.equals("1303963060735762433", qzOrder.getProcessId())) {
				mesCode.append("复合");
			}
			//判断是否是分切工序
			if(StringUtils.equals("1300701063685087234", qzOrder.getProcessId())) {
				String woCode = "";
				if(woCodeList!=null && woCodeList.size()>0) {
					for(String codes:woCodeList) {
						String[] code = codes.split("-");
						woCode = code[0] + "-" + code[1];
						if(StringUtils.equals("WORK-FQ", woCode)) {
							if(!mesCode.toString().contains("分切")) {
								mesCode.append("分切");
								mesCode.append(",");
							}
						}else {
							if(!mesCode.toString().contains("切张")) {
								mesCode.append("切张");
								mesCode.append(",");
							}
						}
					}
				}
			}
			//判断是否是切张工序
			if(StringUtils.equals("1300701144731623426", qzOrder.getProcessId())
					|| StringUtils.equals("1300701196116041729", qzOrder.getProcessId())) {
				mesCode.append("切张");
			}
			mesCode.append(")");
		}
		if(null != template) {
			String id = template.getId();
			List<ZrkPushSet> pushSetList = pushSetService.selectByMessageTemplateId(id);
			if(null != pushSetList && 0 != pushSetList.size()) {
				Iterator<ZrkPushSet> iterator = pushSetList.iterator();
				String message = template.getTemplateContent();
				message = message.replace("${id}", mesCode);
				message = message.replace("${processNo}", orderNo.toString());
				//查找机器号
				ZzDevice zzDevice = zzDeviceService.getById(pickUpBill.getDeviceId());
				String deviceName = "";
				if(zzDevice!=null) {
					deviceName = zzDevice.getDeviceName();
				}
				String customerName = "";
				if(oConvertUtils.isEmpty(qzOrder.getCustomerName())) {
					customerName = "无";
				}else {
					customerName = qzOrder.getCustomerName();
				}
				message = message.replace("${deviceName}", deviceName);
				message = message.replace("${customerName}", customerName);
				List<StkPickUpEntry> list = pickUpEntryService.selectByMainId(pickUpBill.getId());
				if(null == list || 0 == list.size()) {
					return Result.error("未找到提货单明细");
				}
				Iterator<StkPickUpEntry> it = list.iterator();
				StringBuffer info = new StringBuffer();
				info.append("[");
				while(it.hasNext()) {
					StkPickUpEntry entry = it.next();
					info.append("(");
					String categoryId = entry.getMaterialId();
					String name = "";
					if(StringUtils.isBlank(categoryId)){
						categoryId=entry.getCategoryId();
						BasMaterialCategory category = categoryService.getById(categoryId);
						if(category!=null) {
							name = category.getName();
						}
					}else {
						BasMaterial m = materialService.getById(categoryId);
						if(m!=null) {
							name = m.getName();
						}
					}
					String model = "";
					if(oConvertUtils.isEmpty(entry.getModel())) {
						model = "无";
					}else {
						model = entry.getModel();
					}
					BigDecimal num = BigDecimal.ZERO;
					if(oConvertUtils.isNotEmpty(entry.getNumber())) {
						num = entry.getNumber();
					}
					String remark = "";
					if(oConvertUtils.isEmpty(entry.getRemark())) {
						remark = "无";
					}else {
						remark = entry.getRemark();
					}
					info.append("物料名：" + name + ",");
//					info.append("物料编码：" + category.getCode() + ",");
					info.append("规格：" + model + ",");
					info.append("数量：" + num + ",");
					info.append("备注：" + remark + ",");
					info.append(")");
//					if(it.hasNext()) {
//						info.append(",");
//					}
				}
				info.append("]");
				message = message.replace("${info}", info);
				Date date = new Date();
				String messageTime = DateUtils.formatDate(date,"yyyy/MM/dd HH:mm");
				System.err.println(date);
				message = message.replace("${messageTime}", messageTime);
				while(iterator.hasNext()) {
					//查询仓库的管理员和操作员

					ZrkPushSet set = iterator.next();
					String[] userIds = {};
					if(StringUtils.contains(set.getMessageTpe(), pickUpBill.getProcessId())) {
						//查询提醒人钉钉ID
						String userId = set.getUserId();
						userIds = userId.split(",");
					}else {
						continue;
					}
					if(null == userIds||userIds.length==0) {
						log.info("模板未分配用户");
						continue;
					}
					List<String> userIdList = Arrays.asList(userIds);
					List<SysUser> userList = sysUserService.listByIds(userIdList);
					StringBuffer ids = new StringBuffer();
					for(SysUser sysUser:userList) {
						if(null == sysUser) {
							log.info("未找到该用户");
							continue;
						}
						if(StringUtils.isBlank(sysUser.getThirdId())) {
							log.info("该用户未分配第三方id");
							continue;
						}
						ids.append(sysUser.getThirdId());
						ids.append(",");
//						if(flag) {
//							//发送消息成功后,将该任务单状态设置为已推送,防止多次推送（统一消息发送多次在钉钉接口处理的时候会提示143106，该错误码代表发送消息重复，143105:表示企业自建应用每日推送给用户的消息超过上限
//							pickUpBill.setIsPush(1);
//							this.stkPickUpBillService.updateById(pickUpBill);
//							//发送系统消息
//							sysBaseApi.sendSysAnnouncement("admin", sysUser.getUsername(),template.getTemplateName(), message);
//						}
					}
					String userid = ids.toString();
					userid = userid.substring(0,userid.length()-1);
					boolean flag= DingMessageUtils.sendDingMessage(userid, message);
				}
				return Result.ok();
			} else {
				return Result.error("未找到相关人员");
			}
		} else {
			return Result.error("没找到消息模板");
		}
		
	}
	
	private Result<?> sendCheckOutMessage(StkPickUpBill pickUpBill,String orderId) {
		ZzShoporder order = zzShoporderService.getById(orderId);
		String orderNo = "无";
		if(order != null) {
			orderNo = order.getOrderNo();
		}
		//您有新的提货单等待提货，销售单号为：${processNo},机器号：${deviceName},客户名：${customerName},明细为：${info},消息提醒时间：${messageTime},请尽快登录后台管理系统进行提货单出库！
		//取出消息模板
		SysMessageTemplate template = msgTemService.lambdaQuery().eq(SysMessageTemplate::getTemplateCode, "zrk_new_thd").one();
		if(null != template) {
			String id = template.getId();
			List<ZrkPushSet> pushSetList = pushSetService.selectByMessageTemplateId(id);
			if(null != pushSetList && 0 != pushSetList.size()) {
				Iterator<ZrkPushSet> iterator = pushSetList.iterator();
				String message = template.getTemplateContent();
				message = message.replace("${id}", "无");
				message = message.replace("${processNo}", orderNo);
				message = message.replace("${deviceName}", "无");
				ZzShoporder zzShoporder = zzShoporderService.getById(pickUpBill.getOrderId());
				if(zzShoporder==null) {
					return Result.error("未找到生产工单");
				}
				message = message.replace("${customerName}", zzShoporder.getCustomerName());
				List<StkPickUpEntry> list = pickUpEntryService.selectByMainId(pickUpBill.getId());
				if(null == list || 0 == list.size()) {
					return Result.error("未找到提货单明细");
				}
				Iterator<StkPickUpEntry> it = list.iterator();
				StringBuffer info = new StringBuffer();
				info.append("[");
				while(it.hasNext()) {
					StkPickUpEntry entry = it.next();
					info.append("(");
					String categoryId = entry.getMaterialId();
					String name = "";
					if(StringUtils.isBlank(categoryId)){
						categoryId=entry.getCategoryId();
						BasMaterialCategory category = categoryService.getById(categoryId);
						if(category!=null) {
							name = category.getName();
						}
					}else {
						BasMaterial m = materialService.getById(categoryId);
						if(m!=null) {
							name = m.getName();
						}
					}
					String model = "";
					if(oConvertUtils.isEmpty(entry.getModel())) {
						model = "无";
					}else {
						model = entry.getModel();
					}
					BigDecimal num = BigDecimal.ZERO;
					if(oConvertUtils.isNotEmpty(entry.getNumber())) {
						num = entry.getNumber();
					}
					String remark = "";
					if(oConvertUtils.isEmpty(entry.getRemark())) {
						remark = "无";
					}else {
						remark = entry.getRemark();
					}
					info.append("物料：" + name + ",");
//					info.append("物料编码：" + category.getCode() + ",");
					info.append("规格：" + model + ",");
					info.append("数量：" + num + ",");
					info.append("备注：" + remark + ",");
					info.append(")");
//					if(it.hasNext()) {
//						info.append(",");
//					}
				}
				info.append("]");
				message = message.replace("${info}", info);
				String messageTime = DateUtil.format(new Date(),"yyyy/MM/dd hh:mm");
				message = message.replace("${messageTime}", messageTime);
				String tpe = "";
				if(StringUtils.equals(MaterialConstant.PROCESS_COMPOUND, pickUpBill.getProcessId())) {
					tpe = "10";
				}else if(StringUtils.equals(MaterialConstant.PROCESS_PART, pickUpBill.getProcessId())) {
					tpe = "20";
				}else if(StringUtils.equals(MaterialConstant.PROCESS_CUTTING_BIG, pickUpBill.getProcessId())||StringUtils.equals(MaterialConstant.PROCESS_CUTTING_NORMAL, pickUpBill.getProcessId())) {
					tpe = "30";
				}
				//查询仓库的管理员和操作员
				LambdaQueryWrapper<ZrkPushSet> queryWrapper = new LambdaQueryWrapper<ZrkPushSet>();
				queryWrapper.eq(ZrkPushSet::getMessageTpe, tpe);
				ZrkPushSet set = pushSetService.getOne(queryWrapper);
				if(set==null) {
					return Result.error("推送点未设置");
				}
				String[] userIds = {};
				//查询提醒人钉钉ID
				String userId = set.getUserId();
				userIds = userId.split(",");
				if(null == userIds||userIds.length==0) {
					log.info("模板未分配用户");
					return Result.error("模板未分配用户");
					
				}
				List<String> userIdList = Arrays.asList(userIds);
				List<SysUser> userList = sysUserService.listByIds(userIdList);
				StringBuffer ids = new StringBuffer();
				for(SysUser sysUser:userList) {
					if(null == sysUser) {
						log.info("未找到该用户");
						continue;
					}
					if(StringUtils.isBlank(sysUser.getThirdId())) {
						log.info("该用户未分配第三方id");
						continue;
					}
					ids.append(sysUser.getThirdId());
					ids.append(",");
//					if(flag) {
//						//发送消息成功后,将该任务单状态设置为已推送,防止多次推送（统一消息发送多次在钉钉接口处理的时候会提示143106，该错误码代表发送消息重复，143105:表示企业自建应用每日推送给用户的消息超过上限
//						pickUpBill.setIsPush(1);
//						this.stkPickUpBillService.updateById(pickUpBill);
//						//发送系统消息
//						sysBaseApi.sendSysAnnouncement("admin", sysUser.getUsername(),template.getTemplateName(), message);
//					}
				}
				String userid = ids.toString();
				userid = userid.substring(0,userid.length()-1);
				boolean flag= DingMessageUtils.sendDingMessage(userid, message);
				return Result.ok();
			} else {
				return Result.error("未找到相关人员");
			}
		} else {
			return Result.error("没找到消息模板");
		}
		
	}

	@Override
	public Result<?> sendMessage(String ids) {
		ZrkShoporder zrkShoporder = zrkShoporderService.getById(ids);
		if(zrkShoporder!=null) {
			//您有新的任务单等待生产，单号为：${id},客户名：${customerName},产品名：${info},请尽快登录后台管理系统进行查看！
			//取出消息模板
			SysMessageTemplate template = msgTemService.lambdaQuery().eq(SysMessageTemplate::getTemplateCode, "zz_new_shoporder").one();
			if(null != template) {
				String id = template.getId();
				List<ZrkPushSet> pushSetList = pushSetService.selectByMessageTemplateId(id);
				if(null != pushSetList && 0 != pushSetList.size()) {
					LambdaQueryWrapper<ZzShoporder> queryWrapper = new LambdaQueryWrapper<>();
					queryWrapper.eq(ZzShoporder::getOrderNo, zrkShoporder.getOrderNo());
					List<ZzShoporder> list = zzShoporderService.list(queryWrapper);
					if(null == list || 0 == list.size()) {
						return Result.error("未找到任务单");
					}
					Iterator<ZzShoporder> it = list.iterator();
					while(it.hasNext()) {
						ZzShoporder zzShoporder = it.next();
						String message = template.getTemplateContent();
						String code = "";
						if(oConvertUtils.isEmpty(zzShoporder.getWoCode())) {
							code = "无";
						}else {
							code = zzShoporder.getWoCode();
						}
						message = message.replace("${id}", code);
						String customerName = "";
						if(oConvertUtils.isEmpty(zrkShoporder.getCustomerName())) {
							customerName = "无";
						}else {
							customerName = zrkShoporder.getCustomerName();
						}
						message = message.replace("${customerName}", customerName);
						String info = "";
						if(oConvertUtils.isEmpty(zzShoporder.getWoPartname())) {
							info = "无";
						}else {
							info = zzShoporder.getWoPartname();
						}
						message = message.replace("${info}", info);
						String tpe = "";
						if(StringUtils.equals(MaterialConstant.PROCESS_COMPOUND, zzShoporder.getProcessId())) {
							tpe = "40";
						}else if(StringUtils.equals(MaterialConstant.PROCESS_PART, zzShoporder.getProcessId())) {
							tpe = "50";
						}else if(StringUtils.equals(MaterialConstant.PROCESS_CUTTING_BIG, zzShoporder.getProcessId())||StringUtils.equals(MaterialConstant.PROCESS_CUTTING_NORMAL, zzShoporder.getProcessId())) {
							tpe = "60";
						}
						//查询仓库的管理员和操作员
						LambdaQueryWrapper<ZrkPushSet> query = new LambdaQueryWrapper<ZrkPushSet>();
						query.eq(ZrkPushSet::getMessageTpe, tpe);
						ZrkPushSet set = pushSetService.getOne(query);
						if(set==null) {
							return Result.error("推送点未设置");
						}
						String[] userIds = {};
						//查询提醒人钉钉ID
						String userId = set.getUserId();
						userIds = userId.split(",");
						if(null == userIds||userIds.length==0) {
							log.info("模板未分配用户");
							continue;
						}
						List<String> userIdList = Arrays.asList(userIds);
						List<SysUser> userList = sysUserService.listByIds(userIdList);
						StringBuffer idsBuffer = new StringBuffer();
						for(SysUser sysUser:userList) {
							if(null == sysUser) {
								log.info("未找到该用户");
								continue;
							}
							if(StringUtils.isBlank(sysUser.getThirdId())) {
								log.info("该用户未分配第三方id");
								continue;
							}
							idsBuffer.append(sysUser.getThirdId());
							idsBuffer.append(",");
//							if(flag) {
//								//发送消息成功后,将该任务单状态设置为已推送,防止多次推送（统一消息发送多次在钉钉接口处理的时候会提示143106，该错误码代表发送消息重复，143105:表示企业自建应用每日推送给用户的消息超过上限
//								pickUpBill.setIsPush(1);
//								this.stkPickUpBillService.updateById(pickUpBill);
//								//发送系统消息
//								sysBaseApi.sendSysAnnouncement("admin", sysUser.getUsername(),template.getTemplateName(), message);
//							}
						}
						String userid = idsBuffer.toString();
						if(StrUtil.isBlank(userid)) {
							return Result.error("未找到相关人员");
						}
						userid = userid.substring(0,userid.length()-1);
						boolean flag= DingMessageUtils.sendDingMessage(userid, message);
					}
					return Result.ok();
				} else {
					return Result.error("未找到相关人员");
				}
			}else {
				return Result.error("没找到消息模板");
			}
		}else {
			return Result.error("没找到销售订单");
		}
	}

	@Override
	public Result<?> sendDeliveryMessage(String ids) {
		StkIoBill stkIoBill = stkIoBillService.getById(ids);
		if(stkIoBill==null) {
			return Result.error("没找到销售出库单");
		}
		//您有新的销售出库单等待打印，销售单号为：${id},客户名：${customerName},物料明细为：${info},总平方：${totalSquare},请尽快登录后台管理系统进行查看！
		//取出消息模板
		SysMessageTemplate template = msgTemService.lambdaQuery().eq(SysMessageTemplate::getTemplateCode, "zrk_shoporder_out").one();
		if(null == template) {
			return Result.error("没找到消息模板");
		}
		BasCustomer basCustomer = basCustomerService.getById(stkIoBill.getCustomerId());
		String customerName = "无";
		if(basCustomer!=null) {
			customerName = basCustomer.getName();
		}
		String message = template.getTemplateContent();
		String sourceNo = stkIoBill.getSourceNo()==null?"无":stkIoBill.getSourceNo();
		if(oConvertUtils.isEmpty(stkIoBill.getSourceNo())) {
			sourceNo = "无";
		}else {
			sourceNo = stkIoBill.getSourceNo();
		}
		message = message.replace("${id}", sourceNo);
		message = message.replace("${customerName}", customerName);
		String id = template.getId();
		List<ZrkPushSet> pushSetList = pushSetService.selectByMessageTemplateId(id);
		if(null != pushSetList && 0 != pushSetList.size()) {
			List<StkIoBillEntry> list = stkIoBillEntryService.selectByMainId(ids);
			if(null == list || 0 == list.size()) {
				return Result.error("未找到销售出库单明细");
			}
			Iterator<StkIoBillEntry> it = list.iterator();
			StringBuffer info = new StringBuffer();
			info.append("[");
			BigDecimal totalSquare = BigDecimal.ZERO;
			while(it.hasNext()) {
				StkIoBillEntry entry = it.next();
				BasMaterial basMaterial = materialService.getById(entry.getMaterialId());
				String name = "无";
				if(null!=basMaterial) {
					name = basMaterial.getName();
				}
				info.append("(");
				info.append("物料：" + name);
				info.append(")");
				BigDecimal square = entry.getWidth().multiply(entry.getLength());
				totalSquare = totalSquare.add(square); 
			}
			info.append("]");
			message.replace("${totalSquare}", totalSquare.toString());
			LambdaQueryWrapper<ZrkPushSet> query = new LambdaQueryWrapper<ZrkPushSet>();
			query.eq(ZrkPushSet::getMessageTpe, "70");
			ZrkPushSet set = pushSetService.getOne(query);
			if(set==null) {
				return Result.error("推送点未设置");
			}
			String[] userIds = {};
			//查询提醒人钉钉ID
			String userId = set.getUserId();
			userIds = userId.split(",");
			if(null == userIds||userIds.length==0) {
				log.info("模板未分配用户");
				return Result.error("模板未分配用户");
			}
			List<String> userIdList = Arrays.asList(userIds);
			List<SysUser> userList = sysUserService.listByIds(userIdList);
			StringBuffer idsBuffer = new StringBuffer();
			for(SysUser sysUser:userList) {
				if(null == sysUser) {
					log.info("未找到该用户");
					continue;
				}
				if(StringUtils.isBlank(sysUser.getThirdId())) {
					log.info("该用户未分配第三方id");
					continue;
				}
				idsBuffer.append(sysUser.getThirdId());
				idsBuffer.append(",");
//				if(flag) {
//					//发送消息成功后,将该任务单状态设置为已推送,防止多次推送（统一消息发送多次在钉钉接口处理的时候会提示143106，该错误码代表发送消息重复，143105:表示企业自建应用每日推送给用户的消息超过上限
//					pickUpBill.setIsPush(1);
//					this.stkPickUpBillService.updateById(pickUpBill);
//					//发送系统消息
//					sysBaseApi.sendSysAnnouncement("admin", sysUser.getUsername(),template.getTemplateName(), message);
//				}
			}
			String userid = idsBuffer.toString();
			userid = userid.substring(0,userid.length()-1);
			boolean flag= DingMessageUtils.sendDingMessage(userid, message);
		}else {
			return Result.error("消息模板未找到（维护）相关人员");
		}
		return null;
	}

	@Override
	public Result<?> sendOutEndMessage(String ids) {
		StkPickUpBill pickUpBill = stkPickUpBillService.getById(ids);
		if(pickUpBill!=null) {
			//提货已完成，Mes单号为：${id},请尽快登录后台管理系统进行处理！
			//取出消息模板
			SysMessageTemplate template = msgTemService.lambdaQuery().eq(SysMessageTemplate::getTemplateCode, "stk_pick_end").one();
			if(null != template) {
				String id = template.getId();
				List<ZrkPushSet> pushSetList = pushSetService.selectByMessageTemplateId(id);
				if(null != pushSetList && 0 != pushSetList.size()) {
					ZrkQzOrder qzOrder = zrkQzOrderService.getById(pickUpBill.getMesId());
					if(null == qzOrder) {
						return Result.error("未找到mes单");
					}
						String message = template.getTemplateContent();
						String code = "";
						if(oConvertUtils.isEmpty(qzOrder.getCode())) {
							code = "无";
						}else {
							code = qzOrder.getCode();
						}
						message = message.replace("${id}", code);
						//查询仓库的管理员和操作员

						//查询仓库的管理员和操作员
						LambdaQueryWrapper<ZrkPushSet> query = new LambdaQueryWrapper<ZrkPushSet>();
						query.eq(ZrkPushSet::getMessageTpe, "80");
						ZrkPushSet set = pushSetService.getOne(query);
						if(set==null) {
							return Result.error("推送点未设置");
						}
						String[] userIds = {};
						//查询提醒人钉钉ID
						String userId = set.getUserId();
						userIds = userId.split(",");
						if(null == userIds||userIds.length==0) {
							log.info("模板未分配用户");
							return Result.error("模板未分配用户");
						}
						List<String> userIdList = Arrays.asList(userIds);
						List<SysUser> userList = sysUserService.listByIds(userIdList);
						StringBuffer idsBuffer = new StringBuffer();
						for(SysUser sysUser:userList) {
							if(null == sysUser) {
								log.info("未找到该用户");
								continue;
							}
							if(StringUtils.isBlank(sysUser.getThirdId())) {
								log.info("该用户未分配第三方id");
								continue;
							}
							idsBuffer.append(sysUser.getThirdId());
							idsBuffer.append(",");
//							if(flag) {
//								//发送消息成功后,将该任务单状态设置为已推送,防止多次推送（统一消息发送多次在钉钉接口处理的时候会提示143106，该错误码代表发送消息重复，143105:表示企业自建应用每日推送给用户的消息超过上限
//								pickUpBill.setIsPush(1);
//								this.stkPickUpBillService.updateById(pickUpBill);
//								//发送系统消息
//								sysBaseApi.sendSysAnnouncement("admin", sysUser.getUsername(),template.getTemplateName(), message);
//							}
						}
						String userid = idsBuffer.toString();
						userid = userid.substring(0,userid.length()-1);
						boolean flag= DingMessageUtils.sendDingMessage(userid, message);
					return Result.ok();
				} else {
					return Result.error("未找到相关人员");
				}
			}else {
				return Result.error("没找到消息模板");
			}
		}else {
			return Result.error("没找到提货单");
		}
		
	}

	@Override
	public Result<?> sendCreateMesMessage(String ids) {
		// TODO Auto-generated method stub
		//有新的${process}mes单生成，Mes单号为：${id},客户名：${customerName},产品名：${productName},请尽快登录后台管理系统进行处理！
		//根据mes单id获取mes单信息
		ZrkQzOrder qzOrder = zrkQzOrderService.getById(ids);
		if(qzOrder==null) {
			return Result.error("未找到mes单");
		}
		SysMessageTemplate template = msgTemService.lambdaQuery().eq(SysMessageTemplate::getTemplateCode, "zrk_mes_message").one();
		if(null == template) {
			return Result.error("没找到消息模板");
		}
		String id = template.getId();
		String message = template.getTemplateContent();
		//判断生成的是什么mes单
		if(StringUtils.equals(qzOrder.getProcessId(), MaterialConstant.PROCESS_COMPOUND)) {
			message = message.replace("${process}", "复合");
		} else if(StringUtils.equals(qzOrder.getProcessId(), MaterialConstant.PROCESS_PART)) {
			message = message.replace("${process}", "分切");
		}else if(StringUtils.equals(qzOrder.getProcessId(), MaterialConstant.PROCESS_ZJ)) {
			message = message.replace("${process}", "制胶");
		}else if(StringUtils.equals(qzOrder.getProcessId(), MaterialConstant.PROCESS_CUTTING_BIG)||
				StringUtils.equals(qzOrder.getProcessId(), MaterialConstant.PROCESS_CUTTING_NORMAL)) {
			message = message.replace("${process}", "切张");
		}
		message = message.replace("${id}", qzOrder.getCode());
		String customerName = qzOrder.getCustomerName();
		if(oConvertUtils.isEmpty(customerName)) {
			customerName = "无";
		}
		message = message.replace("${customerName}", customerName);
		BasMaterialCategory category = categoryService.getById(qzOrder.getMaterialId());
		String productName = "无";
		if(category!=null) {
			if(oConvertUtils.isNotEmpty(category.getName())) {
				productName = category.getName();
			}
		}
		message = message.replace("${productName}", productName);
		String[] userIds = {};
		//查询提醒人钉钉ID
		String userId = qzOrder.getOperatorUsers();
		userIds = userId.split(",");
		if(null == userIds||userIds.length==0) {
			log.info("mes单未分配操作员");
		}
		List<String> userIdList = Arrays.asList(userIds);
		List<SysUser> userList = sysUserService.listByIds(userIdList);
		//拼接用户第三方id(钉钉id)
		StringBuffer userthirds = new StringBuffer();
		for(SysUser sysUser:userList) {
			if(null == sysUser) {
				log.info("未找到该用户");
				continue;
			}
			if(StringUtils.isBlank(sysUser.getThirdId())) {
				log.info("该用户未分配第三方id");
				continue;
			}
			userthirds.append(sysUser.getThirdId());
			userthirds.append(",");
		}
		String userid = userthirds.toString();
		userid = userid.substring(0,userid.length()-1);
		boolean flag= DingMessageUtils.sendDingMessage(userid, message);
		return Result.ok("发送成功");
	}

	@Override
	public Result<?> sendRecallDeliveryMessage(String ids) {
		// TODO Auto-generated method stub
		ZzShoporder zzShoporder = zzShoporderService.getById(ids);
		if(zzShoporder!=null) {
			//销售单号：${processNo}，客户名：${customerName}，明细：${info}，消息提醒时间：${messageTime}，请尽快登录后台管理系统进行撤单退库！
			//取出消息模板
			SysMessageTemplate template = msgTemService.lambdaQuery().eq(SysMessageTemplate::getTemplateCode, "zz_out_delivery").one();
			if(null != template) {
				String id = template.getId();
				List<ZrkPushSet> pushSetList = pushSetService.selectByMessageTemplateId(id);
				if(null != pushSetList && 0 != pushSetList.size()) {
					ZrkOrderProduct zrkOrderProduct = zrkOrderProductService.getById(zzShoporder.getOrderProdect());
					String message = template.getTemplateContent();
					String processNo = "";
					if(oConvertUtils.isEmpty(zzShoporder.getOrderNo())) {
						processNo = "无";
					}else {
						processNo = zzShoporder.getOrderNo();
					}
					message = message.replace("${processNo}", processNo);
					String customerName = "";
					if(oConvertUtils.isEmpty(zzShoporder.getCustomerName())) {
						customerName = "无";
					}else {
						customerName = zzShoporder.getCustomerName();
					}
					message = message.replace("${customerName}", customerName);
					StringBuffer info = new StringBuffer();
					info.append("[");
					if(oConvertUtils.isEmpty(zzShoporder.getWoPartname())) {
						info.append("物料：无，");
					}else {
						info.append("物料：" + zzShoporder.getWoPartname() + "，");
					}
					if(oConvertUtils.isEmpty(zrkOrderProduct.getProductSpecs())) {
						info.append("规格：无，");
					}else {
						info.append("规格：" + zrkOrderProduct.getProductSpecs() + "，");
					}
					if(oConvertUtils.isEmpty(zrkOrderProduct.getProductCount())) {
						info.append("数量：无，");
					}else {
						info.append("数量：" + zrkOrderProduct.getProductCount() + "，");
					}
					if(oConvertUtils.isEmpty(zrkOrderProduct.getRemark())) {
						info.append("备注：无");
					}else {
						info.append("备注：" + zrkOrderProduct.getRemark());
					}
					info.append("]");
					message = message.replace("${info}", info);
					String messageTime = DateUtil.format(new Date(),"yyyy/MM/dd hh:mm");
					message = message.replace("${messageTime}", messageTime);
					//查询仓库的管理员和操作员
					LambdaQueryWrapper<ZrkPushSet> query = new LambdaQueryWrapper<ZrkPushSet>();
					query.eq(ZrkPushSet::getMessageTpe, "99");
					ZrkPushSet set = pushSetService.getOne(query);
					if(set==null) {
						return Result.error("推送点未设置");
					}
					String[] userIds = {};
					//查询提醒人钉钉ID
					String userId = set.getUserId();
					userIds = userId.split(",");
					if(null == userIds||userIds.length==0) {
						log.info("模板未分配用户");
						return Result.error("模板未分配用户");
					}
					List<String> userIdList = Arrays.asList(userIds);
					List<SysUser> userList = sysUserService.listByIds(userIdList);
					StringBuffer idsBuffer = new StringBuffer();
					for(SysUser sysUser:userList) {
						if(null == sysUser) {
							log.info("未找到该用户");
							continue;
						}
						if(StringUtils.isBlank(sysUser.getThirdId())) {
							log.info("该用户未分配第三方id");
							continue;
						}
						idsBuffer.append(sysUser.getThirdId());
						idsBuffer.append(",");
					}
					String userid = idsBuffer.toString();
					userid = userid.substring(0,userid.length()-1);
					boolean flag= DingMessageUtils.sendDingMessage(userid, message);
//					System.err.println("管理员和操作员：："+userid);
//					System.err.println("消息：：："+message);
					return Result.ok();
				} else {
					return Result.error("未找到相关人员");
				}
			}else {
				return Result.error("没找到消息模板");
			}
		}else {
			return Result.error("没找到生成单");
		}
	}

	@Override
	public void insertPurchaseOrderJobQueue(String id) {
		// TODO Auto-generated method stub
		SysJobQueue jobQueue = new SysJobQueue();
		jobQueue.setQueueInfo(id);
		jobQueue.setQueueCode("purchase_bill_price_change");
		jobQueueService.save(jobQueue);
	}

	@Override
	@Cacheable(value = CacheConstant.SYS_DICT_CACHE,key = "#code+':'+#key")
	public String queryDictTextByKey(String code, String key) {
		return sysDictService.queryDictTextByKey(code, key);
	}

	@Override
	public String queryDictKeyByValue(String text) {
		return sysDictService.queryDictKeyByValue(text);
	}
	
	public String getNoByCode(String code) {
		synchronized (code) {
			SysFillRule rule = fillRuleService.lambdaQuery().eq(SysFillRule::getRuleCode, code).one();
			if(null == rule) {
				return null;
			}
			String params = rule.getRuleParams();
			JSONObject jsonObject = JSONObject.parseObject(params);
			String pre = jsonObject.getString("prefix");
			if(null == pre) {
				pre = StringUtils.EMPTY;
			}
			String period = jsonObject.getString("period");
			Integer seqLen = jsonObject.getInteger("seqLen");
			String numFormatStr = null;
			if(null != seqLen) {
				StringBuffer buffer = new StringBuffer("");
				for (int i = 0; i < seqLen; i++) {
					buffer.append("0");
				}
				numFormatStr = buffer.toString();
			}
			String formatStr = StringUtils.EMPTY;
			if(StringUtils.isNotBlank(period)) {
				SimpleDateFormat format = new SimpleDateFormat(period);
				formatStr = format.format(DateUtil.date());
			}
			String top = StrUtil.strBuilder().append(pre).append(formatStr).toString();
			Integer count = sequenceService.lambdaQuery().eq(BasSequence::getK, top).count();
			if(0 == count) {
				boolean flag = sequenceService.addSequence(top);
				if(flag) {
					Integer seq = sequenceService.getValue(top);
					String last = NumberUtil.decimalFormat(numFormatStr, seq);
					return top + last;
				}
			} else {
				String value = null;
				while(true) {
					Integer seq = sequenceService.getValue(top);
					String last = NumberUtil.decimalFormat(numFormatStr, seq);
					value = top + last;
					Object result = redisUtil.get(value);
					if(null == result) {
						redisUtil.set(value, value, 86400L);
						break;
					}
				}
				return value;
			}
			
			return null;
		}
	}

	@Override
	public Result<?> sendProductedMessage(String orderId) {
		// TODO Auto-generated method stub
		ZrkQzOrder order = zrkQzOrderService.getById(orderId);
		String orderNo = "无";
		if(order != null) {
			orderNo = order.getCode();
		}else {
			log.info("未找到mes单");
		}
		//MES单：${mesNo}，已生产完成，请准备发货。客户名：${customerName},物料：${product},规格：${model},数量：${qty}，消息提醒时间：${messageTime}
		//取出消息模板
		SysMessageTemplate template = msgTemService.lambdaQuery().eq(SysMessageTemplate::getTemplateCode, "producted_message").one();
		if(null != template) {
			String id = template.getId();
			List<ZrkPushSet> pushSetList = pushSetService.selectByMessageTemplateId(id);
			if(null != pushSetList && 0 != pushSetList.size()) {
				Iterator<ZrkPushSet> iterator = pushSetList.iterator();
				String message = template.getTemplateContent();
				message = message.replace("${mesNo}", orderNo);
				StringBuffer productBuffer = new StringBuffer();//物料
				StringBuffer modelBuffer = new StringBuffer();//规格
				StringBuffer qtyBuffer = new StringBuffer();//数量
				//临时存放客户名用以筛除重复客户名
				List<String> customerList = Lists.newArrayList();
				//根据MES单id查询客户关联信息
				StringBuffer customerBuffer = new StringBuffer();//客户
				if(StringUtils.equals("1300701063685087234", order.getProcessId())) {
					//根据mes单id 查询参数
					List<ZrkMesFqParamVO> zrkMesFqParams=zrkMesFqParamService.selectParamBymesId(orderId);
					if(zrkMesFqParams!=null && zrkMesFqParams.size()>0) {
						for(ZrkMesFqParamVO vo:zrkMesFqParams) {
							productBuffer.append(vo.getCategoryName());
							productBuffer.append(",");
							qtyBuffer.append(vo.getQuantity());
							qtyBuffer.append(",");
							String[] models = null;
							if(oConvertUtils.isNotEmpty(vo.getPartParam())) {
								models = StringUtils.split(vo.getPartParam(), "+");
							}
							if(models!=null && models.length>0) {
								for(String model:models) {
									if(oConvertUtils.isNotEmpty(model)) {
										modelBuffer.append(model);
										modelBuffer.append("*");
										modelBuffer.append(vo.getWidth());
										modelBuffer.append(",");
									}
								}
							}
						}
						List<ZrkProductCustomerVO> voList = productCustomerService.selectCustomerByMesId(orderId);
						if(voList!=null && voList.size()>0) {
							for(ZrkProductCustomerVO vo:voList) {
								if(!customerList.contains(vo.getCustomName())) {
									customerBuffer.append(vo.getCustomName());
									customerBuffer.append(",");
								}
								customerList.add(vo.getCustomName());
							}
						}
					}
				}else {
					BasMaterialCategory category = categoryService.getById(order.getMaterialId());
					productBuffer.append(category.getFullname());
					productBuffer.append(",");
					qtyBuffer.append(order.getProductNum());
					qtyBuffer.append(",");
					modelBuffer.append(order.getSpecs());
					modelBuffer.append(",");
					customerBuffer.append(order.getCustomerName());
				}
				message = message.replace("${customerName}", customerBuffer);
				message = message.replace("${product}", productBuffer);
				message = message.replace("${model}", modelBuffer);
				message = message.replace("${qty}", qtyBuffer);
				String messageTime = DateUtil.format(new Date(),"yyyy/MM/dd hh:mm");
				message = message.replace("${messageTime}", messageTime);
				while(iterator.hasNext()) {
					//查询仓库的管理员和操作员

					ZrkPushSet set = iterator.next();
					String[] userIds = {};
					if(oConvertUtils.isNotEmpty(set.getUserId())) {
						//查询提醒人钉钉ID
						String userId = set.getUserId();
						userIds = userId.split(",");
					}else {
						log.info("模板未分配用户");
						continue;
					}
					List<String> userIdList = Arrays.asList(userIds);
					List<SysUser> userList = sysUserService.listByIds(userIdList);
					StringBuffer ids = new StringBuffer();
					for(SysUser sysUser:userList) {
						if(null == sysUser) {
							log.info("未找到该用户");
							continue;
						}
						if(StringUtils.isBlank(sysUser.getThirdId())) {
							log.info("该用户未分配第三方id");
							continue;
						}
						ids.append(sysUser.getThirdId());
						ids.append(",");
					}
					String userid = ids.toString();
					userid = userid.substring(0,userid.length()-1);
					boolean flag= DingMessageUtils.sendDingMessage(userid, message);
					if(flag) {
						return Result.ok("发送成功");
					}else {
						return Result.error("发送失败");
					}
				}
			}else {
				log.info("设置消息提醒未维护");
			}
		}else {
			log.info("消息模板未维护");
		}
		return Result.error("发送失败");
	}

	@Override
	public Result<?> sendCheDanMessage(String mesId) {
		// TODO Auto-generated method stub
		//MES单：${mesNo}，准备撤单。物料编号：${product}，消息提醒时间：${messageTime}
		//取出消息模板
		SysMessageTemplate template = msgTemService.lambdaQuery().eq(SysMessageTemplate::getTemplateCode, "chedan_message").one();
		//mes单
		ZrkQzOrder qzOrder = zrkQzOrderService.getById(mesId);
		if(qzOrder==null) {
			log.info("未找到mes单");
			return Result.error("发送失败");
		}
		//记录生产出库的四种类型
		List<String> productOutTypes = CollUtil.newArrayList("2991", "2992", "2993", "2997");
		//生产出库单
		LambdaQueryWrapper<StkIoBill> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(StkIoBill::getSourceId, mesId);
		queryWrapper.like(StkIoBill::getStockIoType, "299");
		List<StkIoBill> ioBillList = stkIoBillService.list(queryWrapper);
		List<String> idList = Lists.newArrayList();
		List<String> usernameList = Lists.newArrayList();
		if(ioBillList!=null && ioBillList.size()>0) {
			for(StkIoBill stkIoBill:ioBillList) {
				if(CollUtil.contains(productOutTypes, stkIoBill.getStockIoType())) {
					idList.add(stkIoBill.getId());
					usernameList.add(stkIoBill.getCreateBy());
				}
			}
		}
		if(idList!=null && idList.size()>0) {
			//生产出库单明细
			LambdaQueryWrapper<StkIoBillEntry> query = new LambdaQueryWrapper<>();
			query.in(StkIoBillEntry::getMid, idList);
			List<StkIoBillEntry> stkIoBillEntryList = stkIoBillEntryService.list(query);
			List<String> materialIdList = Lists.newArrayList();
			if(stkIoBillEntryList!=null && stkIoBillEntryList.size()>0) {
				for(StkIoBillEntry entry:stkIoBillEntryList) {
					materialIdList.add(entry.getMaterialId());
				}
				StringBuffer buffer = new StringBuffer();
				if(materialIdList!=null && materialIdList.size()>0) {
					List<BasMaterial> materialList = materialService.listByIds(materialIdList);
					if(materialList!=null && materialList.size()>0) {
						for(BasMaterial basMaterial:materialList) {
							buffer.append(basMaterial.getCode());
							buffer.append(",");
						}
						if(template!=null) {
							String message = template.getTemplateContent();
							if(StringUtils.isNotBlank(message)) {
								message = message.replace("${mesNo}", qzOrder.getCode());
							}
							if(buffer!=null && buffer.length()>0) {
								String materialCodes = buffer.toString().substring(0, buffer.length()-1);
								message = message.replace("${product}", materialCodes);
							}
							String messageTime = DateUtil.format(new Date(),"yyyy/MM/dd hh:mm");
							message = message.replace("${messageTime}", messageTime);
							LambdaQueryWrapper<SysUser> queryUser = new LambdaQueryWrapper<>();
							queryUser.in(SysUser::getUsername, usernameList);
							List<SysUser> userList = sysUserService.list(queryUser);
							StringBuffer userIdsBuffer = new StringBuffer();
							if(userList!=null && userList.size()>0) {
								for(SysUser sysUser:userList) {
									if(null == sysUser) {
										log.info("未找到该用户");
										continue;
									}
									if(StringUtils.isBlank(sysUser.getThirdId())) {
										log.info("该用户未分配第三方id");
										continue;
									}
									userIdsBuffer.append(sysUser.getThirdId());
									userIdsBuffer.append(",");
								}
							}
							if(userIdsBuffer!=null && userIdsBuffer.length()>0) {
								String userIds = userIdsBuffer.toString().substring(0, userIdsBuffer.length()-1);
								boolean flag= DingMessageUtils.sendDingMessage(userIds, message);
								if(flag) {
									return Result.ok("发送成功");
								}else {
									return Result.error("发送失败");
								}
							}
						}
					}
				}
			}
		}
		return null;
	}
	
}